/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { loadScript } from '@base/utils';
import { Cascader } from 'antd';
import { isFunction } from 'lodash';
import React, { useEffect, useState } from 'react';
import { CityCascaderType, CityCascaderProps, AreaDataListItem, formatAreaList } from './_utils';

function createDefaultPlaceholder(type: CityCascaderType = 'all'): string {
  const p = ['省', '市', '区'];
  const t = ['province', 'city', 'all'];
  return `选择${p.slice(0, t.findIndex((item) => item === type) + 1).join('')}`;
}

const CityCascader: React.FC<CityCascaderProps> = (props) => {
  const {
    fullName,
    onChange,
    value,
    size,
    type,
    allowClear,
    style,
    placeholder = createDefaultPlaceholder(type),
    disabled = false,
  } = props;
  const [options, setOptions] = useState<AreaDataListItem[]>([]);

  const hasValue = value && !!value.filter((item) => !!item).length;

  useEffect(() => {
    const kb = 'kuaidihelp.com'; // 快宝官方
    const jdk = 'judanke.cn'; // 聚单客
    const hostname = window.location.hostname.includes(jdk) ? jdk : kb;
    loadScript(
      `https://cdn-static.${hostname}/js/pho/${!fullName ? 'min-' : ''}areas.js?v=20221028`,
    ).then(() => {
      const opts = formatAreaList(window.address, type);
      setOptions(opts);
    });
  }, [fullName, type]);

  const handleChange = (v: any[]) => {
    if (isFunction(onChange)) {
      onChange(v);
    }
  };

  const displayRender = (label: string[]) => {
    let index = -1;
    switch (type) {
      case 'province':
        index = 0;
        break;
      case 'city':
        index = 1;
        break;
      default:
        break;
    }
    if (hasValue) {
      const values = value || label;
      return values[index] || values.join('/');
    }
    return '';
  };

  return (
    <Cascader
      style={{ width: '100%', ...style }}
      displayRender={displayRender}
      value={hasValue ? value : []}
      size={size}
      notFoundContent='未匹配到对应区域'
      showSearch
      expandTrigger='hover'
      options={options}
      onChange={handleChange}
      placeholder={placeholder}
      allowClear={allowClear}
      autoFocus={false}
      disabled={disabled}
    />
  );
};

CityCascader.defaultProps = {
  size: 'middle',
  onChange: () => {},
  type: 'all',
  fullName: false,
};

export default CityCascader;
